<template>
  <div ref="chart" class="bar-chart" />
</template>
<script>
import * as echarts from 'echarts'
import { debounce } from '@/utils/index'
export default {
  name: '',
  props: {
    data: {
      type: Array,
      default: () => []
    },
    xAxisData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      chart: null,
      chartResizingWithDebounce: debounce(this.chartResizing, 200)
    }
  },
  computed: {
    generateYAxisScale() {
      const max = Math.max.apply(null, this.data)
      const YAxis = {
        max,
        interval: 1
      }
      if (max <= 10) {
        YAxis.max = 10
        YAxis.interval = 2
      } else {
        YAxis.interval = 10
      }
      return YAxis
    },
    generateOptions() {
      return {
        color: '#2F88FF',
        tooltip: {
          show: true,
          position: 'right',
          formatter: (params) => {
            return `用餐人数：${params?.value}人`
          },
          borderColor: '#fff',
          textStyle: {
            color: '#2F88FF',
            fontSize: 12
          }
        },
        xAxis: {
          type: 'category',
          data: this.xAxisData,
          axisLine: {
            lineStyle: {
              color: '#D8D8D8'
            }
          },
          axisLabel: {
            color: '#303133'
          },
          axisTick: {
            show: false
          }
        },

        yAxis: {
          name: '(人数)',
          type: 'value',
          interval: this.generateYAxisScale.interval,
          min: 0,
          max: this.generateYAxisScale.max,
          axisLabel: {
            color: '#303133'
          },
          axisLine: {
            lineStyle: {
              color: '#303133'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#F5F5F6'
            }
          }
        },
        series: [
          {
            data: this.data,
            type: 'bar',
            barWidth: '21'
          }
        ]
      }
    }
  },
  watch: {
    data: function(data) {
      if (!Array.isArray(data) || data.length <= 0) return []
      this.chart?.setOption?.(this.generateOptions)
    }
  },
  mounted() {
    this.chart = echarts.init(this.$refs.chart)
    this.chart.setOption(this.generateOptions)
    window.addEventListener('resize', this.chartResizingWithDebounce)
  },
  methods: {
    chartResizing() {
      this.chart?.resize?.({
        animation: {
          duration: 1500,
          easing: 'elasticOut'
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

.bar-chart {
  width: 100%;
  height: 300px;
}
</style>
